﻿namespace ResourceBasedAuthApp.Data
{
    public class DocumentRepository
    {
        private static List<DocumentEntity> _documents = new List<DocumentEntity>()
        {
            new DocumentEntity(){ Id=1, Name="史记",Editor="司马迁",LastModify=DateTime.Now , Press="中国人民教育出版社"},
            new DocumentEntity(){ Id=2, Name="资治通鉴",Editor="司马光",LastModify=DateTime.Now , Press="人民文学出版社"},
            new DocumentEntity(){ Id=3, Name="赤壁赋",Editor="苏轼",LastModify=DateTime.Now , Press="商务印书馆"},
            new DocumentEntity(){ Id=4, Name="过秦论",Editor="贾谊",LastModify=DateTime.Now , Press="上海译文出版社"},
            new DocumentEntity(){ Id=5, Name="六国论",Editor="苏洵",LastModify=DateTime.Now, Press="机械工业出版社" }
        };
        public static  DocumentEntity FindById(int id)
        {
            return _documents.FirstOrDefault(item => item.Id.Equals(id));
        }

        public static List<DocumentEntity> GetByName(string  documentName)
        {
            return _documents.Where(item=>item.Name.Contains(documentName)).ToList();   
        }
        public static  bool DeleteById(int id)
        {
            var entity=   FindById(id);
            if (entity!=null)
            {
                return _documents.Remove(entity);
            }
            return false;
         
        }
        public static DocumentEntity Update(DocumentEntity entity)
        {
            var temp = FindById(entity.Id);
            if (entity == null)
            {
                return null;
            }
            temp.Name= entity.Name; 
            temp.Editor= entity.Editor;
            temp.LastModify= entity.LastModify; 
            temp.Press= entity.Press;
            return temp;
        }
        public static DocumentEntity Add(DocumentEntity entity)
        {
            var lastItem = _documents.OrderBy(item => item.Id).Last();
            entity.Id = lastItem.Id + 1;
            entity.LastModify= lastItem.LastModify;
            _documents.Add(entity);
            return entity;
        }

        public static List<DocumentEntity> All()
        {
            return _documents;
        }
    }

    public class DocumentEntity : BaseEntity
    {
        public string Name { get; set; }
        public string Editor { get; set; }
        public string Press { get; set; }
    }


    public class BaseEntity
    {
        public int Id { get; set; }
        public DateTime LastModify { get; set; }
    }
}
